//
//  ChatSearchVC.swift
//  YueChat
//
//  Created by IMac on 2024/10/16.
//

import UIKit

class ChatSearchVC: BaseVC, UISearchBarDelegate {
    
    var searchBar: UISearchBar!
    var searchStr: String?
    
    var conversationInfo: DMCCConversation?

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    convenience init(_ conversationInfo: DMCCConversation) {
        self.init()
        self.conversationInfo = conversationInfo
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: DispatchWorkItem(block: {
            self.searchBar.becomeFirstResponder()
        }))
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 34))
        searchBar.barTintColor = UIColor.red
        searchBar.delegate = self
        

        let searchField = searchBar.value(forKey: "searchField") as? UITextField
        let attrString = NSAttributedString(string: "搜索", attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: searchField?.font ?? UIFont.systemFont(ofSize: 14)])
        searchField?.attributedPlaceholder = attrString
        searchField?.textColor = UIColor.black

        if let imgView = searchField?.leftView as? UIImageView {
            imgView.image = imgView.image?.withRenderingMode(.alwaysTemplate)
            imgView.tintColor = kGrayBG
        }

//        searchBar.reloadInputViews()
        navigationItem.titleView = searchBar

        tableView.register(UINib(nibName: "HomeCell", bundle: nil), forCellReuseIdentifier: "HomeCell")
        
//        searchBar.becomeFirstResponder()
//        registerCellWithNibName(NSStringFromClass(WYSingleCell.self), isTableview: true)
//        registerHeaderFooterWithNibName(NSStringFromClass(WYContactHead.self))

        let backImg = UIImage(named: "Back333")
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: backImg, style: .plain, target: self, action: #selector(back))

        if #available(iOS 9, *) {
            UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.gray], for: .normal)
        }
    }

    @objc func back() {
        dismiss(animated: true, completion: nil)
    }

    override func getData() {
        if dataSource.count == 0 {
            self.view .insertSubview(self.nullView, aboveSubview: self.view)
        }else{
            self.nullView.removeFromSuperview()
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeCell
        let message = dataSource[indexPath.row] as! DMCCMessage
        let userInfo: DMCCUser?

        if message.direction == .Send {
            userInfo = gosnUser.getUserInfoDefault(gosnUser.myId())//DMCCIMService.getInstance().getUserInfo(message.localUser ?? "", inGroup: "", refresh: false)
        } else if conversationInfo?.type == .Single {
            userInfo = gosnUser.getUserInfoDefault(message.target)//MCCIMService.getInstance().getUserInfo(message.target ?? "", inGroup: "", refresh: false)
        } else {
            userInfo = gosnUser.getUserInfoDefault(message.originalUser)//DMCCIMService.getInstance().getUserInfo(message.originalUser ?? "", inGroup: conversationInfo?.targetId ?? "", refresh: false)
        }

//        cell.userInfo = userInfo!
        cell.setUserInfo(userInfo: userInfo!)
        cell.msgRead.isHidden = true
//        cell.timeLab.text = formatTimeLabel(message.timestamp)
        if  message.timestamp > 0 {
            cell.timeLab.text = formatTimeLabel(message.timestamp)
        }
        
        cell.silentImg.isHidden = true;
        cell.redImg.isHidden = true;
        cell.msgRead.isHidden = true;
        
        let content = message.content as! OsnTextMessageContent
        
        // 假设 message.digest 是一个 String 类型的属性
        let digest = NSString(string: content.data)//content.data as? NSString

        // 假设 self.searchStr 是一个非空的 String，这里使用 ! 来强制解包可能是不安全的
        // 更好的做法是确保 self.searchStr 有值，或者使用可选绑定
        if let searchStr = self.searchStr {
            let nsString = digest as NSString
            let range = nsString.range(of: searchStr, options: .caseInsensitive)
            if range.location != NSNotFound {
                let attributedStr = NSMutableAttributedString(string: digest as String)
                attributedStr.addAttribute(.foregroundColor, value: kMainColor, range: range)
                cell.contentLab.attributedText = attributedStr
            } else {
                cell.contentLab.text = content.data
            }
        }
        
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        dismiss()
        let message = dataSource[indexPath.row]
        let vc = ChatVC(conversation: conversationInfo!, msg: message as! DMCCMessage)
        navigationController?.pushViewController(vc, animated: true)
    }

//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let head = tableView.dequeueReusableHeaderFooterView(withIdentifier: NSStringFromClass(WYContactHead.self)) as! WYContactHead
//        head.titleLab.text = KLocalizedString(Chat_records)
//        head.titleLab.font = UIFont.systemFont(ofSize: 14)
//        head.titleLab.textColor = kGray999Color
//        head.contentView.backgroundColor = kWhiteColor
//        return head.contentView
//    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return dataSource.count > 0 ? 30 : 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }


    // UISearchBarDelegate
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        serarchWithStr(searchBar.text ?? "")
        
    }

    func serarchWithStr(_ str: String) {
        let searchStr = str.trimmingCharacters(in: .whitespacesAndNewlines)
        if searchStr.isEmpty {
            MHAlert.showMessage(KLocalizedString("PleaseEnterSearch"))
            return
        }
        self.searchStr = searchStr
//        dataSource = (DMCCIMService.getInstance().selectKeywordMessages(conversationInfo!, keyword: str, page: 0))!
        dataSource = gosnMessage.searchMessage(conversationInfo!.targetId, str)
        getData()
        tableView.reloadData()
        searchBar.resignFirstResponder()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        dismiss()
    }
    
    

    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        searchBar.resignFirstResponder()
    }


}
